package com.sdkx.app.ViewModel;

import android.content.Context;
import android.text.TextUtils;

import com.sdkx.app.MyApp;
import com.sdkx.app.model.WayPoint;
import com.sdkx.app.model.AirWay;
import com.sdkx.app.model.Mark;
import com.sdkx.app.model.ViewObject;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;

/**
 * add by zd
 * 最近使用的管理类
 * 单例类，使用时先调用getInstance()，然后再用此对象去调用方法
 * 注意：被添加的对象必须是已经持久化的，就是id是真实的数据库的存储值
 */
public class NearestUseManager {
    private Context context;
    private final String fileName = "recentuse";
    private static NearestUseManager nearestUseManager;
    private final int MAX_SAVE_COUNT = 20;//最近使用的最大数目

    public static  NearestUseManager getInstance(){
        if (nearestUseManager == null) {
            synchronized (NearestUseManager.class) {
                if (nearestUseManager == null) {
                    nearestUseManager = new NearestUseManager(MyApp.getContext());
                }
            }
        }
        return nearestUseManager;
    }

    private NearestUseManager(Context context) {
        this.context = context;
    }

    //注意：被添加的对象必须是已经持久化的，就是id是真实的数据库的存储值
    public void AddUseObject(ViewObject viewObject) {
        int id = -1;
        String type="";
        //判断当前存储的内容是否超过最大容量
        List<ViewObject> lastContent = getNearestUseObjects();
        int tempCount = lastContent.size()-MAX_SAVE_COUNT;
        if(tempCount>=0) {
            for (int i = 0; i <= tempCount; i++) {
                lastContent.remove(0);
            }
        }
        lastContent.add(viewObject);
        //组成字符串存储
        StringBuilder stringBuilder = new StringBuilder();
        for(ViewObject tempObject :lastContent) {

            if (tempObject instanceof WayPoint) {
                id = ((WayPoint) tempObject).getId();
                type = "WayPoint";
            } else if (tempObject instanceof AirWay) {
                id = ((AirWay) tempObject).getId();
                type = "AirWay";
            } else if (tempObject instanceof Mark) {
                id = ((Mark) tempObject).getId();
                type = "Mark";
            }
            stringBuilder.append(type+","+id+"/r/n");
        }
        save(stringBuilder.toString());
    }

    public List<ViewObject> getNearestUseObjects(){
        List<ViewObject> recentObjectList = new ArrayList<>();
        String allLines = read();
        if(TextUtils.isEmpty(allLines))
            return recentObjectList;
        String[] lines = allLines.split("/r/n");
        for(String line :lines){
            String[] lineArray = line.split(",");
            int id = Integer.parseInt(lineArray[1]);
            switch (lineArray[0]) {
                case "WayPoint":
                    if(id!=-1)
                    {
                        WayPoint wayPoint = WayPointManager.getItem(id);
                        recentObjectList.add(wayPoint);
                    }
                    break;
                case "Mark":
                    if(id!=-1)
                    {
                        Mark mark = MarkManager.getItem(id);
                        recentObjectList.add(mark);
                    }
                    break;
                case "AirWay":
                    if(id!=-1){
                        AirWay airWay = AirWayManager.getItem(id);
                        recentObjectList.add(airWay);
                    }
                    break;
                default:
                    break;
            }
        }
        return recentObjectList;
    }

    //保存数据到文件中
    private void save(String saveData){
        FileOutputStream outputStream = null;
        BufferedWriter writer =null;
        try {
            outputStream = context.openFileOutput(fileName,Context.MODE_PRIVATE);
            writer = new BufferedWriter(new OutputStreamWriter(outputStream));
            writer.write(saveData);
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            if(writer!=null) {
                try {
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    //从文件中读数据
    private String read(){
        StringBuilder content = new StringBuilder();
        FileInputStream inputStream =null;
        BufferedReader reader=null;
        try {
            inputStream = context.openFileInput(fileName);
            reader = new BufferedReader(new InputStreamReader(inputStream));
            String line ="";
            while ((line=reader.readLine())!=null){
                content.append(line);
            }
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            try {
                if(reader!=null)
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return content.toString();
    }
}
